
<div class="layui-card-header">数据管理</div>
<div class="layui-card-body">
    <!-- 更多筛选条件弹窗 -->
    <div class="slideModel" id="dataPreviewModel">
        <fieldset class="layui-elem-field layui-field-title" >
            <legend>数据预览</legend>
        </fieldset>
        <form id="dataPreviewForm" lay-filter="dataPreviewForm" class="layui-form model-form ">
            <div class="layui-inline layui-row year_month_search">
                <label class="layui-form-label">报告期</label>
                <div class="layui-input-block">
                    <input type="text" name="report" class="layui-input" id="reportYear-index" placeholder="请先选择报告期">
                </div>
            </div>
            <div class="report_quarter_search" style="display: none">
                <div class="layui-inline layui-row">
                    <label class="layui-form-label">年</label>
                    <div class="layui-input-block">
                        <select name="report_quarter_year" id="report_quarter_year_search" lay-verify="" lay-filter="report_quarter_year_search">

                        </select>
                    </div>
                </div>
                <div class="layui-inline layui-row">
                    <label class="layui-form-label">季度</label>
                    <div class="layui-input-block">
                        <select name="report_quarter_mouth" id="report_quarter_mounth_search" lay-verify="" lay-filter="report_quarter_mounth_search">
                            <option value="">请选择季度</option>
                            <option value="1">第一季度</option>
                            <option value="2">第二季度</option>
                            <option value="3">第三季度</option>
                            <option value="4">第四季度</option>
                        </select>
                    </div>
                </div>
            </div>
            <div id="chooseVersion-index" style="display: none">
                <label class="layui-form-label">选择版本</label>
                <div class="layui-input-block">
                    <select name="vaersionName" id="version-name-index" lay-filter="version-name-index">

                    </select>
                </div>
            </div>
            <div class="layui-form-item text-left">
                <div id="dataPreviewTmplBox"></div>
            </div>
            <div class="table-content">
                <table class="layui-table" id="searchTable_data">
                    <thead id="searchTable-head">

                    </thead>
                    <tbody id="searchTable-body">

                    </tbody>
                    <div id="idenGroupPageBox"></div>
                </table>
            </div>
        </form>
    </div>
    <div id="dataManage-tmpl-box">

    </div>
</div>
<style>
    .data-title{
        width: inherit;
    }
    .upload-data{
        margin-left: 16px;
    }
</style>
<!--渲染数据管理权限-->
<script type="text/tmpl" id="dataManage-tmpl">
<form class="layui-form">
    <div class="layui-form toolbar">
        <div class="layui-form-item">
             <div class="layui-form-item">
                <label class="layui-form-label data-title">数据导入方式</label>
                <div class="layui-input-block">
                  <select name="dataImportSelect" lay-filter="dataImportSelect">
                    <option value="excel">excel</option>
                    <option value="oracle">oracle</option>
                  </select>
                </div>

                {{ if hasPower("/micro/microMeta/idenManage:queryList")}}
                <button class="layui-btn icon-btn layui-btn-sm upload-data" lay-submit lay-filter="uploadDataBtn" >
                    <i class="layui-icon">&#xe615;</i>数据上传
                </button>
                {{/if}}
                {{ if hasPower("/micro/microMeta/idenManage:queryList")}}
                <button class="layui-btn icon-btn layui-btn-sm" id="showPreviewModel" >
                    …   数据预览
                </button>
                {{/if}}
             </div>
        </div>
    </div>
</form>
</script>
<style>
    .down_load{
        display: flex;
    }
    .down_load .btn-choose{
        margin-right: 10px;
    }
    .down_load .btn-down{
        margin-left: 40px;
    }
    #dataPreviewModel .table-content{
        margin-left: 20px;
    }
    #searchTable_data{
        width: 100%;
        overflow: auto;
        display: inline-block;
    }
    #downloadDataCurrPage{
        margin-left:0;
    }
</style>
<!--渲染指标管理权限-->
<script type="text/tmpl" id="dataPreviewTmpl">
    <div class="layui-form toolbar">
        <div class="layui-form-item">
            <div class="layui-inline down_load">
                <button class="layui-btn btn-down layui-btn-sm layui-btn-primary" id="closeDataPreviewModel">
                    取消
                </button>
                {{ if hasPower("/micro/microMeta/dataManage:filter")}}
                <button class="layui-btn icon-btn layui-btn-sm btn-choose"  id="filterData">
                    <i class="layui-icon">&#xe669;</i>筛选数据
                </button>
                {{/if}}
                {{ if hasPower("/micro/microMeta/dataManage:download")}}
                    <!--<div class="layui-input-block">
                        <select name="method" placeholder="请选择" id="downloadDataSelect" lay-filter="downloadDataSelect">
                            <option value="">下载数据</option>
                            <option value="0">下载当前页</option>
                            <option value="1">下载全部</option>
                        </select>
                    </div>-->

                    <button class="layui-btn icon-btn layui-btn-sm btn-choose" id="downloadDataCurrPage" >
                        <i class="layui-icon">&#xe601;</i>下载当前页
                    </button>
                {{/if}}

            </div>
        </div>
    </div>
</script>
<!--渲染版本-->
<script type="text/tmpl" id="template-pversion-index-tmpl">
    <option value="">请选择版本</option>
     {{each data}}
        <option value="{{$value.id}}">{{$value.pversion}}</option>
    {{/each}}
</script>
<!--渲染表格头部数据-->
<script type="text/tmpl" id="template-searchTable-tmpl">
          <tr>
           {{each t_head}}
             <th style="min-width:{{$value=='单位机构名称'?$value.length*40:$value.length*20}}px" >{{$value}}</th>
            {{/each}}
          </tr>
</script>
<!--渲染季度的年份-->
<script type="text/tmpl" id="template-quarter-tmpl_search">
    <option value="">请选择年份</option>
     {{each dateArr}}
        <option value="{{$value}}">{{$value}}</option>
    {{/each}}
</script>

<script>
    // var powerlist = ["/micro/ident-group:queryList","/micro/ident-group:add"];
    <!--自定义函数判断权限-->
    template.defaults.imports.hasPower = function(data){
        // if(powerlist.includes(data)){
        //     return true;
        // }
        return true;
    };
    layui.use(['layer', 'form', 'admin','table','laypage','laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var table = layui.table;
        var laypage = layui.laypage;
        var laydate = layui.laydate;
        var count = 0;//总个数
        var current=1;//当前页
        var Authorization;
        var urlData = window.mSelUser;  // 列表页面传递的数据，也可以使用top.xxx
        var userInfo = getAuthority();
        var micro_month;
        var micro_year;
        var idenNames = [];
        var idenCodes = [];
        var pversion;
        var stop = false;//防止二次点击
        //获取权限方法
        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;
            getIdenData();
            getReportYear();
        }
        function getReportYear() {
            var date = new Date();
            let new_year = date.getFullYear()-19; //获取完整的年份(4位)
            let dateArr = [];
            for(let i =0;i<19;i++){
                dateArr.push(new_year+=1)
            }
            var str = template("template-quarter-tmpl_search",{dateArr});
            document.getElementById("report_quarter_year_search").innerHTML = str;
            form.render('select')
        }
        getTemplateIdenPower();
        getDataPreviewPower();
        if(urlData.miid.reportType == "1"){
            //年选择器
            laydate.render({
                elem: '#reportYear-index'
                ,type: 'year',done: function(value, date, endDate){
                    micro_month = value.split('-')[1]?value.split('-')[1].replace(/\b(0+)/gi,""):0
                    micro_year = value.split('-')[0]
                    getPverSion();
                }
            });
        }else if(urlData.miid.reportType == "2"){
            laydate.render({
                elem: '#reportYear-index'
                ,type: 'month',
                done: function(value, date, endDate){
                    micro_month = value.split('-')[1]?value.split('-')[1].replace(/\b(0+)/gi,""):0
                    micro_year = value.split('-')[0]
                    getPverSion();
                }
            });
        }else {
            $(".report_quarter_search").css("display","block");
            $(".year_month_search").css("display","none")
            form.on('select(report_quarter_year_search)', function(isMulti){
                micro_year = isMulti.value
            });
            form.on('select(report_quarter_mounth_search)', function(isMulti){
                micro_month = isMulti.value
                if(micro_year){
                    getPverSion()
                }else {
                    layer.msg('请先选择年份', {icon: 2});
                }
            });
        }
        //查询版本
        function getPverSion() {
            if(urlData.miid.datavIsMulti == '0'){
                return false
            }
            $('#chooseVersion-index').css('display','block');
            var req = {
                month:micro_month,
                year:micro_year,
                mitmid:urlData.miid.id
            }
            axios.get(microUrl.microObject.idenDbLink.dataPversion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success") {
                        var data = response.data.data;
                        var str = template("template-pversion-index-tmpl",{data});
                        document.getElementById("version-name-index").innerHTML = str;
                        form.render('select')
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
        //查询指标
        function getIdenData(){
            var req={
                current: 1,
                size: 100,
                miid:urlData.miid.id
            };
            axios.get(microUrl.microObject.idenMicroMeta.idenMicroList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        $.each(data.records,function (index,item) {
                            if(item.idenAliasCode=="NAME"){
                                idenNames.unshift(item.idenName)
                                idenCodes.unshift(item.idenCode)
                            }else{
                                idenNames.push(item.idenName)
                                idenCodes.push(item.idenCode)
                            }
                        })
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
        //获取版本
        form.on('select(version-name-index)', function(data){
            pversion = data.value
        });
        //更多筛选点击
        $('#idenManagePage-morefilter').click(function () {
            openMoreFilterModel();
        })
        $("#showPreviewModel").click(function () {
            $("#dataPreviewModel").slideDown();
            form.render('select')
            return false;
        });
        $("#closeDataPreviewModel").click(function () {
            $("#dataPreviewModel").slideUp();
            return false;
        })
        form.on('select(downloadDataSelect)', function(data){
            if(!micro_month && !micro_year){
                layer.msg('请选择报告期', {icon: 2});
                return false
            }
            if(data.value == '0'){
                DownLoadFile({
                    url:microUrl.microObject.idenDbLink.downLoadIdenData, //请求的url
                    data:{
                        "current": current,
                        "idenCodes": idenCodes,
                        "idenNames": idenNames,
                        "mitmid": urlData.miid.id,
                        "month": micro_month,
                        "pversion": pversion,
                        "size": pageSize,
                        "year": micro_year
                    }//要发送的数据
                });
            }else if(data.value == '1'){
                DownLoadFile({
                    url:microUrl.microObject.idenDbLink.downLoadIdenData, //请求的url
                    data:{
                        "current": 1,
                        "idenCodes": idenCodes,
                        "idenNames": idenNames,
                        "mitmid": urlData.miid.id,
                        "month": micro_month,
                        "pversion": pversion,
                        "year": micro_year,
//                        "size": 99999999999
                        "size":2100000000
                    }//要发送的数据

                });
            }
        });
        $("#downloadDataCurrPage").click(function () {
            if(!micro_month && !micro_year){
                layer.msg('请选择报告期', {icon: 2});
                return false
            }
            DownLoadFile({
                url:microUrl.microObject.idenDbLink.downLoadIdenData, //请求的url
                data:{
                    "current": current,
                    "idenCodes": idenCodes,
                    "idenNames": idenNames,
                    "mitmid": urlData.miid.id,
                    "month": micro_month,
                    "pversion": pversion,
                    "size": pageSize,
                    "year": micro_year
                }//要发送的数据
            });
            return false;
        });
        //下载数据
        function DownLoadFile(options) {
            let xhr = new XMLHttpRequest();
            xhr.open('post', options.url);//指定获取数据的方式和url地址
            xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); // 设置请求头，必须在open后添加
            xhr.setRequestHeader('authorization', Authorization);
            xhr.responseType = 'blob'; // 返回类型blob  blob 存储着大量的二进制数据
            xhr.onload = function (res) {
                if (this.status === 200) {
                    let excelName = decodeURI(xhr.getResponseHeader("filename"));
                    let blob = this.response;
                    let reader = new FileReader();
                    reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签href
                    reader.onload = function (e) {
                        let a = document.createElement('a'); // 转换完成，创建一个a标签用于下载
                        a.download = excelName;
                        a.href = e.target.result;
                        a.click();
                    };
                }
            }
            xhr.send(JSON.stringify(options.data)) //post请求传的参数
        }
        function getSearchData(){
            var req = {
                "current":current,
                "idenCodes": idenCodes,
                "idenNames": idenNames,
                "mitmid": urlData.miid.id,
                "month": micro_month,
                "pversion": pversion,
                "size": pageSize,
                "year": micro_year
            }
            axios({
                method: 'post',
                url:microUrl.microObject.idenDbLink.searchIdenData,
                data:req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success") {
                        var data = response.data.data;
                        getSearchTableData(data)
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
        $("#filterData").click(function () {
            getSearchData();
            return false;
        });

        function getSearchTableData(search_data){
            let t_head = search_data.headNames;
            let t_head_code = search_data.headCodes;
            let t_body = search_data.datas;

            laypage.render({
                elem: 'idenGroupPageBox'
                ,count: search_data.count,
                limit:pageSize,
                groups:1,
                curr:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(obj.curr!=current){
                        current = obj.curr;
                        getSearchData();
                    }
                }
            });

            var str = template("template-searchTable-tmpl",{t_head});
            document.getElementById("searchTable-head").innerHTML = str;
            $.each(t_body,function (index,item) {
               let table_tr = document.createElement("tr")
                $("#searchTable-body").append(table_tr)
            })
            $("#searchTable-body tr").each(function (index,item) {
                let table_td = "";
                if(!t_body.length){
                    table_td = ""
                }else {
                    $.each(t_head_code,function (n,m) {
                        let value = (t_body[index][m]==null)?'-':t_body[index][m];
                        table_td += "<td>"+value+"</td>"
                    })
                }
                $($("#searchTable-body tr")[index]).html(table_td)
            })

            table.render({
                elem: '#searchTable_data',
                size: 'sm'
            });

        }
        form.on('select(dataImportSelect)', function(data){
        });
        form.on('submit(uploadDataBtn)', function(data){
            if(data.field.dataImportSelect == "excel"){
                showExcelDataUploadModel();
            }else if(data.field.dataImportSelect == "oracle"){
                showOracleDataUploadModel();
            }
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。

        });

        /*渲染指标管理权限*/
        function getTemplateIdenPower() {
            var str = template("dataManage-tmpl",{});
            document.getElementById("dataManage-tmpl-box").innerHTML = str;

            form.render('select')
        }

        /*渲染数据预览权限*/
        function getDataPreviewPower() {
            var str = template("dataPreviewTmpl",{});
            document.getElementById("dataPreviewTmplBox").innerHTML = str;
        }
        /*显示更多筛选框*/
        function openMoreFilterModel() {
            $("#idenManagePageMoreFilterModel").slideDown();
            form.render('select');
        }
        /*显示excle数据上传框*/
        function showExcelDataUploadModel() {
            window.miid = {
                miid:urlData.miid
            };
            admin.open({
                title: 'excel数据上传',
                url: 'dataManage/excelDataUpload.html',
//                area:['400px','400px'],
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }
        /*显示Oracle数据上传框*/
        function showOracleDataUploadModel() {
            admin.open({
                title: 'oracle数据库上传',
                url: 'dataManage/oracleDataUpload.html',
                area:['400px','600px'],
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }

    });
</script>
